<template>
  <div class="mb-switcher van-cell van-cell-clear" v-show="visible" >
    <van-cell :title="title" :required="required">
      <van-switch v-model="value" size="24px" :disabled="readonly" @change="onchange"/>
    </van-cell>
  </div>
</template>

<script>
import { request } from 'utils/http'
export default {
  name: 'mb-swticher',
  data() {
    return {
      visible: true,
      value: null,
      value_display: this.result_display,
      switcher: []
    }
  },
  props: ['item','result','result_display'],
  computed: {
    title() {
      return this.item.caption || this.item.name || ''
    },
    required() {
      return this.item.required
    },
    readonly() {
      return this.item.readonly
    }
  },
  watch: {
    value: function(newVal) {
      let emitObj = {};
      emitObj[this.item.name] = this.toBoolean(newVal);
      emitObj[(this.item.name + "_display")] = this.value_display;
      this.$emit("formChange", this.item.name, emitObj, this.item);
    }
  },
  methods: {
    init() {
      if(!this.item) return
      const _this = this;
      request(this.item.url, {
        query: {
          sign: this.item.supportSigns,
          time: this.item.time
        }
      }).then(res => {
        if(res.code !== "0") {
          this.$notify({ type: 'danger', message: '获取' + _this.title + '信息失败' });
          return
        }
        if(res.datas && res.datas.code && res.datas.code.rows) {
          _this.switcher = res.datas.code.rows;
          _this.switcher = _this.switcher.map( item => {
            item.id = _this.toBoolean(item.id);
            return item
          });
        }
      })
    },
    /**
     *  如果[this.switcher]为true与false之外的其他字符串(失控场景)，默认第一项为是(true)，第二项为否(false)
     */
    onchange(checked) {
      const target = this.switcher.filter(item => {
        return item.id === checked
      });
      if(target && target.length) {
        this.value_display = target[0].name;
      } else if (this.switcher.length) {
        this.value_display = checked ? this.switcher[0].name : this.switcher[1].name;
      }
    },
    /**
     *  将诸如“true”和“false”、“0”和“1”、0和1的数据转化为boolean值；
     */
    toBoolean(key) {
      // 为防止返回值出现字符串“true”和“false”、“0”和“1”、0和1的场景
      switch(key) {
        case "true":
        case "1": 
        case 1:
          key = true;
          break;
        case "false":
        case "0": 
        case 0:
          key = false;
          break;
        default:
          break;
      }
      return key
    },
    validate() {
      return true
    }
  },
  mounted() {
    let emitObj = {};
    emitObj[this.item.name] = this.result || false;
    emitObj[(this.item.name + "_display")] = this.result_display;
    this.$emit("formChange", this.item.name, emitObj, this.item);
    this.init();
  }
}
</script>
<style>
.mb-switcher .van-switch {
  float: right;
}
</style>